import axios from 'axios';
import type {
  Character,
  Conversation,
  ApiResponse,
  GenerateCharacterRequest,
  CreateConversationRequest,
  SendMessageRequest,
  ConversationDetailResponse,
  SendMessageResponse,
} from '@/types/roleplay';

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log('API请求:', config.method?.toUpperCase(), config.url);
    return config;
  },
  (error) => {
    console.error('API请求配置失败:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log(
      'API响应:',
      response.status,
      response.config.url,
      response.data
    );
    return response.data;
  },
  (error) => {
    console.error('API请求失败:', error);
    throw error;
  }
);

// 角色相关API
export const characterApi = {
  // 生成新角色
  async generate(
    data: GenerateCharacterRequest
  ): Promise<ApiResponse<Character>> {
    return api.post('/characters/generate', data);
  },

  // 获取所有角色
  async getAll(): Promise<ApiResponse<Character[]>> {
    return api.get('/characters');
  },

  // 获取单个角色
  async getById(id: string): Promise<ApiResponse<Character>> {
    return api.get(`/characters/${id}`);
  },

  // 更新角色
  async update(
    id: string,
    data: Partial<Character>
  ): Promise<ApiResponse<Character>> {
    return api.put(`/characters/${id}`, data);
  },

  // 删除角色
  async delete(id: string): Promise<ApiResponse> {
    return api.delete(`/characters/${id}`);
  },
};

// 对话相关API
export const conversationApi = {
  // 创建新对话
  async create(
    data: CreateConversationRequest
  ): Promise<ApiResponse<Conversation>> {
    return api.post('/conversations', data);
  },

  // 获取角色的所有对话
  async getByCharacterId(
    characterId: string
  ): Promise<ApiResponse<Conversation[]>> {
    return api.get(`/conversations/character/${characterId}`);
  },

  // 获取对话详情
  async getById(id: string): Promise<ApiResponse<ConversationDetailResponse>> {
    return api.get(`/conversations/${id}`);
  },

  // 发送消息
  async sendMessage(
    conversationId: string,
    data: SendMessageRequest
  ): Promise<ApiResponse<SendMessageResponse>> {
    return api.post(`/conversations/${conversationId}/messages`, data);
  },

  // 删除对话
  async delete(id: string): Promise<ApiResponse> {
    return api.delete(`/conversations/${id}`);
  },
};
